import Taro,{Component} from '@tarojs/taro'
import { View, Text, Button } from '@tarojs/components'
import styles from './index.module.scss'
import { getDetailByTask, submitOrderByTask, updateOrderByTask, getProtocolByTask, uploadFile, clockIn } from '@/api/index'
import { filter, dialog } from '@/util/index'
import { AtModal, AtModalHeader, AtModalContent, AtModalAction, AtIcon} from 'taro-ui'
import { connect } from '@tarojs/redux'
import { setUrl } from '@/actions/web'
import bmap from '@/util/bmap-wx.min.js'
import { BMapAk, MINX_URL } from '@/api/config'

@connect(({user}) => ({
  info: user.info,
  isSign: user.isSign
}), dispatch => ({
  setUrl: (data) => dispatch(setUrl(data)),
}))
export default class TaskDetail extends Component {

  config = {
    navigationBarTitleText: '任务详情'
  }

  state = {
    data: '',
    isDialog: false,
    dialogContent: '',
    taskNumber: '',
    checked: true,
    uploadName: '',
    uploadPath: '',
    statusList: {
      1: '未接单',
      2: '进行中',
      3: '待验收',
      4: '已驳回',
      5: '已验收',
      6: '已完成',
      7: '已取消',
      8: '已关闭'
    },
    address: '',
    clockInSuccess: false
  }

  componentDidMount = () => {
    const {id, scene} = this.$router.params
    let taskNumber = id || decodeURIComponent(scene)
    if (taskNumber) {
      this.setState({taskNumber: filter.trim(taskNumber, 2)}, () => {
        this.getData()
      })
    } else {
      Taro.showToast({title: 'taskNumber参数为空', icon: 'none'})
    }
  }

  openGps = () => {
    wx.getLocation({
      type: 'gcj02',
      success:(res) => {
        this.getGeo()
      },
      fail: (e) => {
        dialog.toast({title: '获取定位失败，请重新定位'})
      }
    })
  }

  getSetting = () => {
    let that = this
    wx.getSetting({
      success: (res) => {
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] == undefined) {
          this.openGps()
        } else if (res.authSetting['scope.userLocation'] == false) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    console.log(dataAu)
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      that.getGeo();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else{
          this.getGeo()
        }
      }
    })
  }

  getGeo = () => {
    let that = this
    const BMap = new bmap.BMapWX({ak: BMapAk})
    let fail = (data) => console.log(data)
    let success = (data) => {
      let originalData = data.originalData
      let wxMarkerData = data.wxMarkerData
      if (originalData.status === 0) {
        this.clockInSync(wxMarkerData[0].latitude, wxMarkerData[0].longitude, wxMarkerData[0].address)
      } else {
        wx.showModal({
          title: '百度地图提示',
          content: '错误码：' + originalData.status
        })
      }
    }
    BMap.regeocoding({
      fail: fail,
      success: success,
      iconPath: '../assets/img/marker_red.png',
      iconTapPath: '../assets/img/marker_red.png'
    })
  }

  clockInSync = async (lat, lng, address) => {
    try {
      const { taskNumber } = this.state
      const { data } = await clockIn({taskNumber, lat, lng})
      this.setState({clockInSuccess: true, address})
      dialog.toast({title: '定位成功'})
    } catch (e) {
      dialog.toast({title: e.message})
    }
  }

  getData = async () => {
    try {
      const { isSign, info } = this.props
      const { taskNumber } = this.state
      let loginAccount = isSign ? info.mobile : undefined
      const { data } = await getDetailByTask({taskNumber, loginAccount})
      this.setState({data})
    } catch (e) {
      Taro.showToast({title: e.message, icon: 'none'})
    }
  }

  /**
   * @description 弹窗 - 交付任务
   */
  showDialog = () => {
    this.setState({isDialog: true})
  }

  /**
   * @description 立即接单
   * @param {*}
   */
  async AcceptOrder() {
    try {
      const { taskNumber, checked } = this.state
      if (!checked) return
      const { isSign, info } = this.props
      if (!this.login()) return
      let loginAccount = isSign ? info.mobile : undefined
      Taro.showLoading({mask: true, title: '接单中'})
      const { data } = await submitOrderByTask({loginAccount, taskNumber})
      Taro.hideLoading()
      dialog.toast({title: '接单成功'})
      this.setState({id: 1}, () => {
        this.getData()
      })
    } catch (e) {
      dialog.toast({title: e.message})
    }
  }

  login() {
    const { isSign } = this.props
    if (!isSign) {
      Taro.showModal({
        title: '提示',
        content: '账户未登录',
        success: function(res) {
          if (res.confirm) {
            Taro.navigateTo({url: '/pages/login/index'})
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return false
    }
    return true
  }

  closeDialog = (callback) => {
    this.setState({isDialog: false, dialogContent: '', uploadName: '', uploadPath: '', address: ''}, () => {
      if (callback) {
        callback()
      } else {
        return
      }
    })
  }

  upLoadFileByFile = async () => {
    const { uploadPath } = this.state
    if (!uploadPath) return this.confirmDialog()
    let res = await Taro.uploadFile({
      url: MINX_URL('/common/upload'),
      filePath: uploadPath,
      name: 'file',
      header: {
        'Content-Type': 'multipart/form-data'
      },
    })
    if (res.statusCode === 200) {
      const result = JSON.parse(res.data)
      if (result.code === 0) {
        this.setState({uploadPath: result.url}, () => {
          this.confirmDialog()
        })
      }
    } else {
      dialog.toast({title: '上传失败'})
    }
  }

  /**
   * @description 交付任务
   * @param {address, deliveryAccessories, taskDeliveryDescription, status, orderNumber}
   */
  confirmDialog = async() => {
    try {
      const { dialogContent, address, uploadPath, clockInSuccess } = this.state
      const { orderNumber, onSiteCheckIn } = this.state.data
      if (!dialogContent) return dialog.toast({title: '请输入交付内容'})
      if (onSiteCheckIn === '1' && !clockInSuccess) return dialog.toast({title: '请完成定位'})
      Taro.showLoading({mask: true, title: '交付任务中...'})
      const { data } = await updateOrderByTask({orderNumber, status: 3, taskDeliveryDescription: dialogContent, address, deliveryAccessories: uploadPath})
      Taro.hideLoading()
      dialog.toast({title: '交付成功'})
      this.closeDialog(() => {
        this.getData()
      })
    } catch (e) {
      Taro.showToast({title: e.message, icon: 'none'})
    }
  }

  /**
   * @description 取消任务
   */
  cancelOrder = async () => {
    try {
      const { orderNumber } = this.state.data
      Taro.showLoading({mask: true, title: '交付中'})
      const { data } = await updateOrderByTask({orderNumber, status: 7})
      Taro.hideLoading()
      dialog.toast({title: '已取消任务'})
      this.setState({isDialog: false, dialogContent: ''}, () => {
        this.getData()
      })
    } catch (e) {
      Taro.showToast({title: e.message, icon: 'none'})
    }
  }

  toggleChecked = () => {
    this.setState(pre => ({checked: !pre.checked}))
  }

  getProtocol = async(id) => {
    try {
      Taro.showLoading({title: '正在跳转协议...'})
      const { data } = await getProtocolByTask({id})
      Taro.hideLoading()
      this.props.setUrl(data)
      Taro.navigateTo({url: '/pages/web/index'})
    } catch (e) {
      Taro.showToast({title: e.message, icon: 'none'})
    }
  }

  uploadFile = () => {
    let _this = this
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success: (res) => {
        const tempFilePaths = res.tempFiles
        if (tempFilePaths[0].type !== 'file') return dialog.title({title: '请上传文件'})
        this.setState({uploadName: tempFilePaths[0].name, uploadPath: tempFilePaths[0].path})
      },
      fail(err) {
        dialog.toast({title: e.errMsg})
      }
    })
  }

  initUpload = () =>{
    this.setState({uploadPath: '', uploadName: ''})
  }

  render() {
    const { data, isDialog, dialogContent, checked, uploadName, uploadPath, statusList, address } = this.state
    const { isSign }= this.props
    return (
      <View className={styles.wrapper}>
        <View className={styles.box}>
          <View className={styles.item}>
            <Text className={styles.grey}>任务名称</Text>
            <Text className={styles.value}>{data.taskName}</Text>
          </View>
          <View className={styles.item}>
            <Text className={styles.grey}>预计费用</Text>
            <Text className={`${styles.value} ${styles.red}`}>￥{data.taskEstimatedCost}</Text>
          </View>
          <View className={styles.item}>
            <Text className={styles.grey}>任务时长</Text>
            <Text className={styles.value}>{data.taskDuration}</Text>
          </View>
          {data.onSiteCheckIn === '1' && <View className={styles.item}>
            <Text className={styles.grey}>任务地址</Text>
            <Text className={styles.value}>{data.userSignInAddress}</Text>
          </View>}
          <View className={styles.item}>
            <Text className={styles.grey}>开始时间</Text>
            <Text className={styles.value}>{data.taskBeginTime}</Text>
          </View>
          <View className={styles.item}>
            <Text className={styles.grey}>结束时间</Text>
            <Text className={styles.value}>{data.taskEndTime}</Text>
          </View>
        </View>

        <View className={styles.box}>
          <View className={styles.title}>任务描述</View>
          <View className={styles.content+' '+styles.borderBottom}>描述：{data.taskDescribe}</View>
          <View className={styles.item}>
            <Text className={styles.grey}>任务编号</Text>
            <Text className={styles.value}>{data.taskNumber}</Text>
          </View>
          <View className={styles.item}>
            <Text className={styles.grey}>发布时间</Text>
            <Text className={styles.value}>{data.createTime}</Text>
          </View>
          <View className={styles.item}>
            <Text className={styles.grey}>发布商户</Text>
            <Text className={styles.value}>{data.merchantName}</Text>
          </View>
        </View>
        {/* 1未接单  2进行中 3待验收 4：已驳回 5：已验收 6:已完成 7：已取消 8: 已关闭*/}
        {
          (isSign && data.status !== 1) && <View style={'margin-top:10px'}>
            <View className={styles.box}>
              <View className={styles.item}>
                <Text className={styles.grey}>接单编号</Text>
                <Text className={styles.value}>{data.orderNumber}</Text>
              </View>
              <View className={styles.item}>
                <Text className={styles.grey}>接单时间</Text>
                <Text className={styles.value}>{data.orderTime}</Text>
              </View>
            </View>

            {data.taskDeliveryDescription && <View className={styles.box}>
              <View className={styles.title}>交付内容</View>
              <View className={styles.content}>{data.taskDeliveryDescription}</View>
            </View>}

            {[4,5,6].includes(data.status) && <View className={styles.box}>
              <View className={styles.title}>验收信息</View>
              {data.status !== 4 && <View className={styles.subtitle}>商户{statusList[data.status]}</View>}
              <View className={styles.content}>确认结算费用：<Text className={styles.red}>￥{data.acceptanceAmount}</Text></View>
              <View className={styles.desc}>{data.acceptanceNotes}</View>
            </View>}
          </View>
        }

        {((!isSign && data.contractId) || (data.status === 1 && data.contractId)) && <View className={styles.protocolWrapper}>
          <Label onClick={() => this.toggleChecked()}>
            <Checkbox checked={checked}></Checkbox>我已阅读并同意
          </Label>
          <Text decode={true} className={styles.theme} onClick={(e) => {e.stopPropagation();this.getProtocol(data.contractId)}}>《{data.contractTitle}》</Text>
        </View>}

        {([1,2,4,7].includes(data.status) || !isSign) && <View className={styles.btnWrapper}>
          { data.status === 2 && <Button className={styles.cancel} onClick={this.cancelOrder}>取消任务</Button> }
          { (data.status === 1 || !isSign) && <Button className={`${styles.confirm} ${!checked? styles.disabled : ''}`} onClick={this.AcceptOrder}>立即接单</Button> }
          { data.status === 2 && <Button className={styles.confirm} onClick={this.showDialog}>交付任务</Button> }
          { data.status === 4 && <Button className={styles.confirm} onClick={this.showDialog}>重新交付</Button> }
          { data.status === 7 && <Button className={styles.confirm} onClick={this.AcceptOrder}>重新接单</Button> }
        </View> }

        <AtModal isOpened={isDialog} onClose={() => this.setState({isDialog : false})}>
          <AtModalContent>
            {
              isDialog && <Textarea
                placeholder='填写交付任务内容...'
                style={'width:100%;background:rgba(250, 250, 250, 1);border-radius: 2px;padding: 12px;box-sizing: border-box;height: 245px;'}
                placeholderStyle={'color: rgba(204, 204, 204, 1);font-size: 14px;'}
                maxlength={300}
                value={dialogContent}
                onInput={(e) => this.setState({dialogContent: e.detail.value})}>
              </Textarea>
            }
            <View className={styles.upload}>
              <Text className={styles.uploadText}>上传附件（微信里选择文件）</Text>
              {data.onSiteCheckIn === '1' && <Text className={styles.uploadText}>GPS定位</Text>}
            </View>
            <View className={styles.upload}>
              <View className={styles.item}>
                {
                  !uploadPath ? <View className={styles.fileUpload} onClick={this.uploadFile}></View> : <View className={styles.fileContent}>
                    <View className={styles.fileImg}><AtIcon value={'iconfont icon-file'} size={28}></AtIcon></View>
                    <Text>{uploadName}</Text>
                    <View className={styles.close} onClick={this.initUpload}><AtIcon value={'iconfont icon-close'} size={12} color="red"></AtIcon></View>
                  </View>
                }
              </View>
              {
                data.onSiteCheckIn === '1' && <View className={styles.item}>
                  {
                    address ? <Text>{address}</Text> : <View className={styles.clock} onClick={this.getSetting}>{'点击\n定位'}</View>
                  }
                </View>
              }
            </View>
          </AtModalContent>
          <AtModalAction><Button onClick={() => this.closeDialog()}>取消</Button> <Button onClick={() => this.upLoadFileByFile()}>确定</Button> </AtModalAction>
        </AtModal>
      </View>
    )
  }
}
